package bancosys.tec.rtm.impl.diagnostician;

import java.util.List;

import jmine.tec.persist.jms.TestMessageSender;
import jmine.tec.persist.jms.dao.JMSMonitoringMessageDAO;
import jmine.tec.persist.jms.domain.JMSMonitoringMessage;
import bancosys.tec.persist.controller.TransactionalController;
import bancosys.tec.rtm.diagnostician.AbstractDiagnostician;
import bancosys.tec.rtm.diagnostician.DiagnosisBean;

/**
 * Diagnosticador que executa testes com as filas pré-programadas.
 */
public class MDBMonitoringDiagnostician extends AbstractDiagnostician {

    private final String connectionFactory;

    private final String[] queues;

    private final TransactionalController controller;

    /**
     * Construtor.
     * 
     * @param controller TransactionalController
     * @param connectionFactory JMS da Connection Factory
     * @param queues Array de Strings com JMS das Filas
     */
    public MDBMonitoringDiagnostician(TransactionalController controller, String connectionFactory, String[] queues) {
        this.controller = controller;
        this.connectionFactory = connectionFactory;
        this.queues = queues;
    }

    /**
     * {@inheritDoc}
     */
    public String getName() {
        return "Filas e MDBs";
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected boolean fillDiagnosisBean(DiagnosisBean bean) throws Exception {
        JMSMonitoringMessageDAO dao = this.controller.getDAOFactory().getDAOByClass(JMSMonitoringMessageDAO.class);
        List<JMSMonitoringMessage> msgs = dao.findLatest();
        for (JMSMonitoringMessage msg : msgs) {
            bean.addDescription(msg.toString());
        }

        // Remove mensagens antigas.
        msgs = dao.findOld();
        for (JMSMonitoringMessage msg : msgs) {
            msg.getPersister().remove();
        }

        return true;
    }

    /**
     * Envia mensagens de testes para processamento e posterior impressão no diagnóstico.
     */
    public void sendTestMessages() {
        TestMessageSender sender = new TestMessageSender(this.controller);
        for (String queue : this.queues) {
            sender.sendTestMessage(this.connectionFactory, queue);
        }
    }

}
